<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="排查时间" prop="remarkSpare1">
        <el-date-picker clearable size="small"
          v-model="queryParams.remarkSpare1"
          type="month"
          value-format="yyyy-MM"
          placeholder="选择排查时间" style="width: 180px">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="排查部门" prop="deptId">
        <treeselect v-model="queryParams.deptId" :options="deptOptions" :show-count="true" placeholder="请选择排查部门" style="width: 180px"/>
      </el-form-item>
      <el-form-item label="排查人员" prop="createBy">
        <el-select  v-model="queryParams.createBy" filterable placeholder="选择排查人员" style="width: 180px">
          <el-option
            v-for="user in filteredUsers"
            :key="user.userId+''"
            :label="user.nickName "
            :value="user.userId+''">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="判定依据" prop="remark">
        <el-select  v-model="queryParams.remark" filterable placeholder="选择判定依据" style="width: 180px">
          <el-option
            v-for="content in allBasis"
            :key="content.id+''"
            :label="content.basis"
            :value="content.id+''">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['risk:inspection:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['risk:inspection:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['risk:inspection:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['risk:inspection:export']"
        >导出</el-button>
        <el-button
          type="primary"
          plain
          icon="el-icon-edit"
          size="mini"
          @click="onSaveOrBack"
        >返回</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="inspectionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" width="50" align="center" >
        <template slot-scope="scope">
          <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <!--      <el-table-column label="主键ID" align="center" prop="id" />-->
      <el-table-column label="排查时间" align="center" prop="remarkSpare1" />
      <el-table-column label="判定依据" align="center" prop="inspectionTime" />
      <el-table-column label="排查内容" align="center" prop="source"/>
      <el-table-column label="排查情况" align="center" prop="remarkSpare2" />
      <el-table-column label="排查结果" align="center" prop="remarkSpare" :formatter="remarkSpareFormat"/>
      <el-table-column label="整改措施" align="center" prop="inspectionSituation" />
      <el-table-column label="排查部门" align="center" prop="deptName" />
      <el-table-column label="排查人员" align="center" prop="createBy" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['risk:inspection:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['risk:inspection:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改重大隐患自查清单对话框 -->
    <el-dialog :title="addtitle" :close-on-click-modal="false" :visible.sync="addopen" width="800px" append-to-body>
      <el-form ref="addform" :model="addform" :rules="addrules" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12" :xs="24">
            <el-form-item label="排查时间" prop="remarkSpare1">
              <el-date-picker clearable size="small"
                              v-model="addform.remarkSpare1"
                              type="month"
                              value-format="yyyy-MM"
                              placeholder="选择排查时间" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="排查部门" prop="deptId">
              <treeselect v-model="addform.deptId" :options="deptOptions" :show-count="true" placeholder="请选择排查部门" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :span="12" :xs="24">
            <el-form-item label="排查人员" prop="createBy">
              <el-select  v-model="addform.createBy" filterable placeholder="选择排查人员" style="width: 100%">
                <el-option
                  v-for="user in filteredUsers"
                  :key="user.userId+''"
                  :label="user.nickName "
                  :value="user.userId+''">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="判定依据" prop="remark">
<!--              <el-input v-model="form.inspectionTime"  type="textarea" :disabled="true"  />-->

                            <el-select  v-model="addform.remark" filterable placeholder="选择判定依据" @change="handleSelectChange" style="width: 100%">
                              <el-option
                                v-for="content in allBasis"
                                :key="content.id+''"
                                :label="content.basis"
                                :value="content.id+''">
                              </el-option>
                            </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="排查内容" prop="inspectionProject">
<!--          <el-input v-model="form.source"  type="textarea" :disabled="true" placeholder="请输入排查内容" />-->
                    <el-select  v-model="addform.inspectionProject" filterable placeholder="选择排查内容" @change="handleSelectChange1"  style="width: 100%">
                      <el-option
                        v-for="content in contentList"
                        :key="content.id+''"
                        :label="content.content"
                        :value="content.id+''">
                      </el-option>
                    </el-select>
        </el-form-item>
        <el-form-item label="排查情况" prop="remarkSpare2">
          <el-input v-model="addform.remarkSpare2" type="textarea" placeholder="请输入排查情况" />
        </el-form-item>
        <el-form-item label="排查结果" prop="remarkSpare">
          <el-select v-model="addform.remarkSpare" placeholder="请选择排查结果" style="width: 100%">
            <el-option
              v-for="dict in remarkSpareOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
          <!--          <el-input v-model="form.remarkSpare" placeholder="请输入备用" />-->
        </el-form-item>
        <el-form-item label="整改措施" prop="inspectionSituation">
          <el-input v-model="addform.inspectionSituation" type="textarea" placeholder="请输入整改措施" />
        </el-form-item>
        <!--        <el-form-item label="依据标准" prop="sourceIds">-->
        <!--          <el-select v-model="form.sourceIds" multiple placeholder="请选择依据标准" style="width: 100%">-->
        <!--            <el-option-->
        <!--              v-for="dict in sourceIdOptions"-->
        <!--              :key="dict.dictValue"-->
        <!--              :label="dict.dictLabel"-->
        <!--              :value="dict.dictValue"-->
        <!--            ></el-option>-->
        <!--          </el-select>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="备注" prop="remark">-->
        <!--          <el-input v-model="form.remark" placeholder="请输入备注" />-->
        <!--        </el-form-item>-->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitaddForm">确 定</el-button>
        <el-button @click="addcancel">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="24">
          <el-col :span="12" :xs="24">
            <el-form-item label="排查时间" prop="remarkSpare1">
              <el-date-picker clearable size="small"
                              v-model="form.remarkSpare1"
                              type="month"
                              value-format="yyyy-MM"
                              placeholder="选择排查时间" style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="排查部门" prop="deptId">
              <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择排查部门" :disabled="true" style="width: 100%"/>
            </el-form-item>
          </el-col>
        </el-row>
          <el-row :gutter="24">
          <el-col :span="12" :xs="24">
            <el-form-item label="排查人员" prop="createBy">
              <el-select  v-model="form.createBy" filterable placeholder="选择排查人员" :disabled="true" style="width: 100%">
                <el-option
                  v-for="user in filteredUsers"
                  :key="user.userId+''"
                  :label="user.nickName "
                  :value="user.userId+''">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :xs="24">
            <el-form-item label="判定依据" prop="inspectionTime">
              <el-input v-model="form.inspectionTime"  type="textarea" :disabled="true"  />

<!--              <el-select  v-model="form.remark" filterable placeholder="选择判定依据" :disabled="true" style="width: 100%">-->
<!--                <el-option-->
<!--                  v-for="content in allBasis"-->
<!--                  :key="content.id+''"-->
<!--                  :label="content.basis"-->
<!--                  :value="content.id+''">-->
<!--                </el-option>-->
<!--              </el-select>-->
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="排查内容" prop="source">
          <el-input v-model="form.source"  type="textarea" :disabled="true" placeholder="请输入排查内容" />
<!--          <el-select  v-model="form.inspectionProject" filterable placeholder="选择排查内容" style="width: 100%">-->
<!--            <el-option-->
<!--              v-for="content in contentList"-->
<!--              :key="content.id+''"-->
<!--              :label="content.content"-->
<!--              :value="content.id+''">-->
<!--            </el-option>-->
<!--          </el-select>-->
        </el-form-item>
        <el-form-item label="排查情况" prop="remarkSpare2">
          <el-input v-model="form.remarkSpare2" type="textarea" placeholder="请输入排查情况" />
        </el-form-item>
        <el-form-item label="排查结果" prop="remarkSpare">
          <el-select v-model="form.remarkSpare" placeholder="请选择排查结果" style="width: 100%">
            <el-option
              v-for="dict in remarkSpareOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
          <!--          <el-input v-model="form.remarkSpare" placeholder="请输入备用" />-->
        </el-form-item>
        <el-form-item label="整改措施" prop="inspectionSituation">
          <el-input v-model="form.inspectionSituation" type="textarea" placeholder="请输入整改措施" />
        </el-form-item>
<!--        <el-form-item label="依据标准" prop="sourceIds">-->
<!--          <el-select v-model="form.sourceIds" multiple placeholder="请选择依据标准" style="width: 100%">-->
<!--            <el-option-->
<!--              v-for="dict in sourceIdOptions"-->
<!--              :key="dict.dictValue"-->
<!--              :label="dict.dictLabel"-->
<!--              :value="dict.dictValue"-->
<!--            ></el-option>-->
<!--          </el-select>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="备注" prop="remark">-->
<!--          <el-input v-model="form.remark" placeholder="请输入备注" />-->
<!--        </el-form-item>-->

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInspection, getInspection, delInspection, addInspection, updateInspection, exportInspection, optionselect ,overtimeControl} from "@/api/risk/inspection";
import { allList,allContentList } from "@/api/risk/content";
import Treeselect from '@riophae/vue-treeselect'
import { treeselect } from "@/api/system/dept";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { getCurrentUser, listUserNoPage } from "@/api/system/user";
import { allBasis, listOption } from "@/api/risk/basis";

export default {
  name: "InspectionDetail",
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      changeParams: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 重大隐患自查清单表格数据
      inspectionList: [],
      // 危险源ID字典
      sourceIdOptions: [],
      remarkSpareOptions: [],
      contentList: [],
      deptOptions: undefined,
      filteredUsers:[],
      allBasis: [],
      // 弹出层标题
      title: "",
      addtitle: "",
      // 是否显示弹出层
      open: false,
      addopen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        remarkSpare1: null,
        deptId: null,
        createBy: null,
      },
      createBy: "",
      deptId: "",
      // 表单参数
      form: {},
      addform: {},
      // 表单校验
      rules: {
        inspectionProject: [
          { required: true, message: "排查内容不能为空", trigger: "blur" }
        ],
        remarkSpare: [
          { required: true, message: "排查结果不能为空", trigger: "blur" }
        ],
        remarkSpare1: [
          { required: true, message: "排查时间不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "排查部门不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "排查人员不能为空", trigger: "blur" }
        ],
        remarkSpare2: [
          { required: true, message: "排查情况不能为空", trigger: "blur" }
        ],
      },
      addrules: {
        inspectionProject: [
          { required: true, message: "排查内容不能为空", trigger: "blur" }
        ],
        remarkSpare: [
          { required: true, message: "排查结果不能为空", trigger: "blur" }
        ],
        remarkSpare1: [
          { required: true, message: "排查时间不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "排查部门不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "排查人员不能为空", trigger: "blur" }
        ],
        remarkSpare2: [
          { required: true, message: "排查情况不能为空", trigger: "blur" }
        ],
        remark: [
          { required: true, message: "判定依据不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getCurrentUser();
    // this.getList();
    this.getTreeselect();
    // this.getContent();
    this.fetchUsers();
    this.getallBasis();
    this.getDicts("investigation_situation").then(response => {
      this.remarkSpareOptions = response.data;
    });
  },
  watch: {
    '$route': {
      handler: function (to, from) {
        // 当路由发生变化时会调用这个方法
        // 你可以在这里处理参数变化

        if(to.params.remarkSpare1){
          console.log('参数变化了:', to.params.remarkSpare1);
          const remarkSpare1 = to.params.remarkSpare1;
          this.queryParams.remarkSpare1 = remarkSpare1;
          this.changeParams = true;
        }
        if(to.params.deptId){
          console.log('参数变化了:', to.params.deptId);
          const deptId = to.params.deptId;
          this.queryParams.deptId = deptId;
          this.changeParams = true;
        }
        if(to.params.createBy){
          console.log('参数变化了:', to.params.createBy);
          const createBy = to.params.createBy;
          this.queryParams.createBy = createBy+'';
          this.changeParams = true;
        }
        if(to.params.remark){
          console.log('参数变化了:', to.params.remark);
          const remark = to.params.remark;
          this.queryParams.remark = remark+'';
          this.changeParams = true;
        }
        if (this.changeParams){
          this.getList();
        }
      },
      // 如果需要深度监听路由参数，可以设置deep: true
      deep: true
    }
  },
  mounted() {
    // 获取传递的参数
    const remarkSpare1 = this.$route.params.remarkSpare1;
    console.log('参数:', remarkSpare1);
    this.queryParams.remarkSpare1 = remarkSpare1;
    const deptId = this.$route.params.deptId;
    console.log('参数:', deptId);
    this.queryParams.deptId = deptId;
    const createBy = this.$route.params.createBy;
    console.log('参数:', createBy);
    if (createBy) {
      this.queryParams.createBy = createBy + '';
    }
    const remark = this.$route.params.remark;
    console.log('参数:', remark);
    if (remark) {
      this.queryParams.remark = remark + '';
    }
    this.getList();
  },
  methods: {
    /** 查询重大隐患自查清单列表 */
    getList() {
      this.loading = true;
      listInspection(this.queryParams).then(response => {
        this.inspectionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
      optionselect().then(response => {
        this.sourceIdOptions = response.data;
      });
      this.overtime();
    },
    getContent(value) {
      allContentList(value).then(response => {
          this.contentList = response.data;
        }
      );
      console.log(this.contentList)
    },
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
        // console.log('this.deptOptions:' + JSON.stringify(this.deptOptions))
      });
    },
    getCurrentUser() {
      let currentUser = this.$store.state.user;
      getCurrentUser(currentUser.userId).then(response => {
        this.createBy = response.data.userId
        this.deptId = response.data.deptId
      });
    },
    fetchUsers() {
      this.loading=true;
      listUserNoPage().then(response => {
          this.filteredUsers = response.rows;
          this.loading = false;
        }
      );
    },
    getallBasis() {
      listOption().then(response => {
          this.allBasis = response.data;
        }
      );
      console.log(this.allBasis)
    },
    overtime() {
      overtimeControl().then(response => {
        if (response.code === 200) {

        } else {
          this.msgError(response.msg);
        }
      })
    },
    sourceFormat(row, column) {
      return this.selectDictLabels(this.sourceIdOptions, row.source);
    },
    remarkSpareFormat(row, column) {
      return this.selectDictLabel(this.remarkSpareOptions, row.remarkSpare);
    },
    inspectionProjectFormat(row, column) {
      const content = this.contentList.find(content => content.id + '' === row.inspectionProject);
      return content ? content.content : '';
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    addcancel() {
      this.addopen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        inspectionTime: null,
        inspectionProject: null,
        inspectionSituation: null,
        source: null,
        remark: null,
        remarkSpare: null,
        remarkSpare1: null,
        remarkSpare2: null,
        createBy: null,
        createTime: null,
        deptId: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
      this.addform = {
        id: null,
        inspectionTime: null,
        inspectionProject: null,
        inspectionSituation: null,
        source: null,
        remark: null,
        remarkSpare: null,
        remarkSpare1: null,
        remarkSpare2: null,
        createBy: null,
        createTime: null,
        deptId: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("addform");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.addform.createBy = this.createBy+'';
      this.addform.deptId = this.deptId;
      var now = new Date();
      var month = now.getMonth()+1;
      var year = now.getFullYear();
      this.addform.remarkSpare1 = year + "-" + month;
      this.addopen = true;
      this.addtitle = "添加重大隐患自查清单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getInspection(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改重大隐患自查清单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.remarkSpare === "2"){
            if(this.form.inspectionSituation === null || this.form.inspectionSituation === ""){
              this.$modal.msgError(`整改措施不能为空`);
              return false;
            }
          }
          if (this.form.id != null) {
            updateInspection(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addInspection(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    submitaddForm() {
      this.$refs["addform"].validate(valid => {
        if (valid) {
          if (this.addform.remarkSpare === "2"){
            if(this.addform.inspectionSituation === null || this.addform.inspectionSituation === ""){
              this.$modal.msgError(`整改措施不能为空`);
              return false;
            }
          }
          // if (this.form.id != null) {
          //   updateInspection(this.form).then(response => {
          //     this.msgSuccess("修改成功");
          //     this.open = false;
          //     this.getList();
          //   });
          // } else {
            addInspection(this.addform).then(response => {
              this.msgSuccess("新增成功");
              this.addopen = false;
              this.getList();
            });
          // }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除选中的重大隐患自查清单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delInspection(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有重大隐患自查清单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          // return exportInspection(queryParams);
        this.download('/risk/inspection/export', {
          ...this.queryParams
        }, `重大隐患自查清单.xlsx`)
        this.exportLoading = false;
        }).then(response => {
          // this.download(response.msg);
          // this.exportLoading = false;
        }).catch(() => {});
    },
    handleSelectChange(value) {
      const selectedOption = this.allBasis.find(option => option.id+'' === value);
      this.addform.inspectionTime = selectedOption.basis;
      this.addform.inspectionProject = '';
      this.getContent(value);
    },
    handleSelectChange1(value) {
      const selectedOption = this.contentList.find(option => option.id+'' === value);
      this.addform.source = selectedOption.content;
    },
    onSaveOrBack(){

      this.$router.replace({ path: '/redirect' }).then(() => {
        this.$router.replace({ path: '/risk/inspection' });
      });

      // this.$router.push("/risk/inspection").then(() => {
      //
      // //  window.location.reload();
      //   this.$router.go(0);
      // });
    }

  }
};
</script>
